/**
 * UserService.java
 * Version 1.0.0
 * Created on 2018年7月11日
 *
 */
package com.yincheng.oes.sso.service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yincheng.oes.sso.entity.User;
import com.yincheng.oes.sso.entity.UserRole;
import com.yincheng.oes.sso.mapper.UserMapper;
import com.yincheng.oes.sso.mapper.UserRoleMapper;

/**
 * @author yangsy
 * @version 1.0.0
 * @since
 * 创建时间：2018年7月11日
 * 功能描述：用户服务类
 * 邮箱地址：446948434@qq.com
 */
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    /**
     * 保存用户信息，如果已存在则更新用户信息
     *
     * @param user
     */
    public void saveUser(User user) {
        int key = userMapper.update(user);
        if (key == 0) {
            user.setCreateTime(new Date());
            user.setValid("1");// 默认激活
            userMapper.insert(user);
        }
    }

    /**
     * 修改用户状态
     *
     * @param userId
     */
    public void changeUserStatus(String userId) {
        userMapper.changeUserStatus(userId);
    }

    /**
     * 根据账号获取用户信息
     *
     * @param userAccount
     * @return
     */
    public User getUserByUserAccount(String userAccount) {
        User user = userMapper.selectByUserAccount(userAccount);
        return user;
    }

    /**
     * 获取所有用户信息列表
     *
     * @return
     */
    public List<User> getAllUserList() {
        List<User> users = userMapper.selectAllUsers();
        return users;
    }

    /**
     * 创建学生用户
     *
     * @param user
     */
    @Transactional
    public void createStudentUser(User user) {
        String userId = UUID.randomUUID().toString();
        user.setCreateTime(new Date());
        user.setTelephone(user.getUserAccount());
        user.setUserId(userId);
        user.setValid("1");
        userMapper.insert(user);

        UserRole userRole = new UserRole();
        userRole.setId(UUID.randomUUID().toString());
        userRole.setUserId(userId);
        userRole.setRoleId("2");// 学生角色id
        userRoleMapper.insert(userRole);
    }
}
